package com.ticket.sass.common.ticketserver

import org.springframework.beans.BeansException
import org.springframework.beans.factory.DisposableBean
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component
import kotlin.jvm.Throws

/**
 * @author 朱其鹏
 * @date 2022/6/2 上午11:48
 */
@Component
class SpringContextHolder : ApplicationContextAware, DisposableBean {
    companion object {
        private var applicationContext: ApplicationContext? = null

        @Throws(BeansException::class)
        fun <T>getBean(name: Class<T>): T {
            return applicationContext?.getBean(name)
                ?: error("不能存在的方法 $name")
        }

        @Throws(BeansException::class)
        fun getBean(name: String): Any {
            return applicationContext?.getBean(name)
                ?: error("不能存在的方法 $name")
        }

        fun getBeanDefinitionNames(): List<String>? {
            return applicationContext?.beanDefinitionNames?.toList()
        }
    }

    override fun setApplicationContext(context: ApplicationContext) {
        applicationContext = context
    }

    override fun destroy() {
        applicationContext = null
    }
}